package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
/**
 * 经传多盈
 */
public class N8n8BbsAnalyse implements AnalyseNews{

	
	public boolean isDetailPage(String url){
		boolean bRet = false;
		String[] regex = {
				"http://guba.n8n8.cn/[a-z0-9]*/[0-9]*/",
				"http://bbs.n8n8.cn/topic-[0-9]*.shtml"
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta bbs = new NewsMeta();
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		bbs.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		String author = null;
		Integer clickNum=0;
		Integer commentNum=0;

		Document doc = Jsoup.parse(htmltxt);
		title = doc.select("div#J-postCont h4.post-tit").text();
		if(StringUtils.isBlank(title)){
			title = doc.select("strong.s_tit").text();
		}
		content = HtmlCleaner.getContentHtml(url,  doc.select("div#J-postCont div.post-cnt-all"));
		if(StringUtils.isBlank(content)){
			Element firstCon = doc.select("div.t_wrap").first();
			if(firstCon!=null) {
				content = HtmlCleaner.getContentHtml(url, firstCon);
			}
		}
		date = DateUtils.matchDate(doc.select("div#J-postCont span.date").text());
		if(date==null){
			Element firstDate = doc.select("span.time").first();
			if(firstDate!=null) date = DateUtils.matchDate(firstDate.text());

		}
		author= doc.select("div#J-postCont span.name").text();
		if(StringUtils.isBlank(author)){
			Element firstName = doc.select("p.name").first();
			if(firstName!=null) author = firstName.text();
		}

		clickNum = NumberUtils.matchNumber(doc.select("#hits_info").text());
		commentNum = NumberUtils.matchNumber(doc.select("#reply_info").text());
		bbs.setClickNum(clickNum);
		bbs.setCommentNum(commentNum);
		bbs.setTitle(StringUtils.trimSpace(title));
		bbs.setContent(content);
		bbs.setDate(date);
		bbs.setAuthor(author);
		bbs.setUpdateUrl(url);
		return bbs;
	}
	
	public NewsMeta Update(NewsMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}
    
	
}
